package meijuli.com.join51.business.setpaypwd

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import meijuli.com.join51.business.R
import com.jhx.common.framework.QuickBaseFragment
import meijuli.com.join51.business.ui.widget.PwdEditText
import com.jhx.common.utils.ToastUtil
import kotlinx.android.synthetic.main.activity_paypwd.*
import me.foji.anko.clear

/**
 * 设置交易密码
 *
 * @author Jack 2018-01-26 16:17
 */
class SetPayPwdFragment : QuickBaseFragment() {

    override fun bindView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return inflater.inflate(R.layout.activity_paypwd, container, false)
    }

    @SuppressLint("MissingSuperCall")
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        if (arguments != null) {
            val type = arguments?.getInt(PayPwdActivity.KEY_TYPE)
            if (type == PayPwdActivity.SET_PASSWORD) {
                text_message.text = "请设置6位数字交易密码"
            } else {
                text_message.text = "正在重置交易密码"
            }
        }

        text_confirm.visibility = View.GONE

        pwdEditText.setOnInputListener(object : PwdEditText.OnInputListener {
            override fun onInput(text: CharSequence) {

            }

            override fun onInputFinish(text: CharSequence) {
                if(!checkPwd(text.toString())) {
                    ToastUtil.getInstance().showToast(activity,"密码不能是重复、连续的数字")
                    pwdEditText.clear()
                    return
                }
                val bundle = Bundle()
                bundle.putString(PayPwdActivity.KEY_CODE, arguments?.getString(PayPwdActivity.KEY_CODE))
                bundle.putString(PayPwdActivity.KEY_PHONE, arguments?.getString(PayPwdActivity.KEY_PHONE))
                bundle.putString(ConfirmPwdFragment.KEY_PWD, text.toString())
                push(ConfirmPwdFragment::class.java, bundle)
                pwdEditText.clear()
            }
        })
    }

    /**
     * 检测密码, 不能是连续、重复的数字
     */
    private fun checkPwd(pwd: String?): Boolean {
        val array = pwd?.toCharArray()
        if(array != null && array.size > 1) {
            (0 until array.size - 2)
                    .filter { array[it] != array[it +1] && Math.abs(array[it] - array[it +1]) != 1 }
                    .forEach { return true }
        }
        return false
    }

}